package com.atguigu.study.pool;

import java.util.concurrent.*;

//ThreadPoolExecutor
public class ThreadPoolDemo {
    public static void main(String[] args) {
        // Cpu密集型 复杂运算 线程数应设cpu核数+1
        // I/O密集型 运算简单 数量大 线程数应设cpu核数* 2
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
                1,//Runtime.getRuntime().availableProcessors(),  得到Cpu核数
                 5,//Runtime.getRuntime().availableProcessors()+1, Runtime.getRuntime().availableProcessors()*2,
                1L,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
        try {
            for (int i = 1; i <= 8; i++) {
                int finaI=i;
                threadPool.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"\t"+"为:"+finaI+"\t客户办业务");
                });
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            threadPool.shutdown();
        }
    }
    public static void defaultPool(){
        ExecutorService executorService = Executors.newFixedThreadPool(5);//线程固定
        // ExecutorService executorService = Executors.newSingleThreadExecutor();//线程为一
        //ExecutorService executorService = Executors.newCachedThreadPool();//一池多线程 会自动扩线程
        try {
            for (int i = 1; i <= 20; i++) {
                int finaI=i;
                executorService.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"\t"+"为:"+finaI+"\t客户办业务");
                });
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            executorService.shutdown();
        }
    }
}
